'use strict';

const { Service } = require('ee-core');
const Storage = require('ee-core/storage');
const { random } = require("lodash");
const { buildTree, resOk } = require("../utils/tools");
const Log = require("ee-core/log");
const { createByTree } = require("../utils/fileTools");
const fs = require("node:fs");
const path = require("path")
const { v4: uuidv4 } = require('uuid');
const { readExcel, createDeptAndUsersList } = require("../utils/analysisExcel");
const pinyin = require('pinyin');

/**
 * dept service
 */

class deptService extends Service {
	constructor(props) {
		super(props);
		this.jsonFile = 'dept';
		this.deptDB = Storage.connection(this.jsonFile);
		this.deptDBKey = {
			dept: 'department',
			user: 'user',
			dw: 'danwei'
		};
		this.valiDeptNull()
	}

	/**
	 * 数据库为空
	 * @returns {[{name: string, id: string}]}
	 */
	valiDeptNull() {
		if (!this.deptDB.db.has('department').value()) {
			this.deptDB.db.set('department', []).write();
		}
		if (!this.deptDB.db.has('danwei').value()) {
			this.deptDB.db.set('danwei', []).write();
		}
		if (!this.deptDB.db.has('user').value()) {
			this.deptDB.db.set('user', []).write();
		}
	}

	// 获取全部组织树
	async getAllDepts() {
		let dw = this.deptDB.db
			.get('danwei')
			.value();
		let dept = this.deptDB.db
			.get('department')
			.value();
		if (dw.length > 0 && dept.length > 0) {
			let tree = JSON.parse(JSON.stringify([...dw, ...dept]))
			return resOk(buildTree(tree))
		} else {
			return resOk([]);
		}
	}


	/**
	 * 获取组织树
	 */
	async getDeptTreeData() {
		let dw = this.deptDB.db
			.get('danwei')
			.value();
		let dept = this.deptDB.db
			.get('department')
			.value();
		if (Object.values(data).length > 0) {
			let tree = JSON.parse(JSON.stringify([...dw, ...dept]))
			Log.info(tree)
			return resOk(buildTree(tree))
		} else {
			return resOk([]);
		}
	}

	uploadExcel(data) {
		const { file } = data
		let excelData = readExcel(file)
		let dbData = {
			danwei:this.deptDB.db.get('danwei').value(),
			dept:this.deptDB.db.get('department').value()
		}

		// 解析文件
		let obj = createDeptAndUsersList(excelData,dbData) // 机构 部门 人员

		// 写入数据库
		let users = obj.userList
		let depts = obj.deptList
		let danwei = obj.danweiList
		danwei.forEach((item) => {
			const existingDanwei = this.deptDB.db.get('danwei').value();
			if (!existingDanwei.some(dw => dw.id === item.id)) {
				this.deptDB.db.get('danwei').push(item).write();
			}
		})
		depts.forEach((item) => {
			const existingDept = this.deptDB.db.get('department').value();
			if (!existingDept.some(dept => dept.id === item.id)) {
				this.deptDB.db.get('department').push(item).write();
			}
		})
		users.forEach((item) => {
			this.deptDB.db.get('user').push(item).write()
		})
		return resOk()
	}

	getUser() {
		let user = this.deptDB.db.get('user').value()
		return resOk(user)
	}

	deleteDept(data){
		// 单位id
		const { id } = data;
		// 根据单位ID获取所有关联部门
		const depts = this.deptDB.db.get('department').value();
		const relatedDepts = depts.filter(dept => dept.parentId === id);
		
		// 删除单位
		this.deptDB.db.get('danwei').remove({ id }).write();
		
		// 删除关联部门
		relatedDepts.forEach(dept => {
			this.deptDB.db.get('department').remove({ id: dept.id }).write();
		});
		// 获取所有用户
		const users = this.deptDB.db.get('user').value();
		// 删除关联部门下的所有人员
		relatedDepts.forEach(dept => {
			users.filter(user => user.deptId === dept.id).forEach(user => {
				this.deptDB.db.get('user').remove({ id: user.id }).write();
			});
		});
		return resOk()
	}
	
	clearCache(){
		this.deptDB.db.set('danwei', []).write();
		this.deptDB.db.set('department', []).write();
		this.deptDB.db.set('user', []).write();
	}

	reloadUserPinyin(){
		let user = this.deptDB.db.get('user').value()
		user.forEach(item => {
			item.pinyin = pinyin.pinyin(item.name).map(it=>it[0][0]).join('').toUpperCase()
		})
		this.deptDB.db.set('user', user).write();
	}
}

deptService.toString = () => '[class deptService]';
module.exports = deptService;
